<script setup lang="ts">

import {SidebarMenuButton} from "@/components/ui/sidebar";
import {Button} from "@/components/ui/button";
import {computed, ref} from "vue";
import {CircleIcon, SearchIcon} from "lucide-vue-next";
import {
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator
} from "@/components/ui/command";
import {useRouter} from "vue-router";
import {NavMenu, NavGroup} from "@/types/nav";
import {navGroups} from "@/constants/menus";

const openCommand = ref(false)
const router = useRouter()

const openApisNav = computed<NavGroup | undefined>(() => {
  return navGroups
      .flatMap((nav: NavMenu) => nav.items)
      .find((item: NavGroup) => item.title === 'Application')
})


function handleSelectedLink(link: string) {
  router.push(link);
  openCommand.value = false;
}

</script>

<template>
  <SidebarMenuButton as-child tooltip="Search">
    <Button variant="outline" size="sm" class="text-xs" @click="openCommand = !openCommand">
      <SearchIcon/>
      <span class="font-normal group-data-[collapsible=icon]:hidden">Search anythings</span>
    </Button>
  </SidebarMenuButton>

  <CommandDialog v-model:open="openCommand">
    <CommandInput placeholder="Type a command or search..."/>
    <CommandList>
      <CommandEmpty>No results found.</CommandEmpty>
      <CommandGroup heading="Suggestions">
        <CommandItem value="Home" @select="handleSelectedLink('/')">
          Home
        </CommandItem>
        <CommandItem value="Application" @select="handleSelectedLink('/application')">
          Application
        </CommandItem>
      </CommandGroup>
      <CommandSeparator/>

      <CommandGroup heading="OpenApis">
        <CommandItem
            v-for="nav in openApisNav?.children"
            :key="nav.title"
            :value="nav.title"
            class="gap-2"
            @select="handleSelectedLink(nav.link)"
        >
          <CircleIcon/>
          {{ nav.title }}
        </CommandItem>
      </CommandGroup>
    </CommandList>
  </CommandDialog>
</template>

<style scoped>

</style>
